from http import cookies
import json
from lib2to3.pgen2 import token
from msilib.schema import Error
from pickle import FALSE
import re
from time import sleep, time
import requests
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
import random
import pymongo

myclient = pymongo.MongoClient(
    "mongodb://admin:admin@192.168.3.21:27017/?serverSelectionTimeoutMS=5000&connectTimeoutMS=10000")
mydb = myclient["mp_weixin"]

user = 'snowboardinghome@163.com'
password = 'Snow2022.'


def mp_weixin_login():
    post = {}
    broswer = webdriver.Chrome()
    broswer.get("https://mp.weixin.qq.com/")
    sleep(10)
    broswer.delete_all_cookies()
    sleep(2)
    broswer.find_element(
        By.XPATH, "//a[@class='login__type__container__select-type']").click()
    sleep(5)
    # 模拟用户点击
    print("请手动登录")
    input_user = broswer.find_element(By.XPATH, "//input[@name='account']")
    input_user.send_keys(user)
    sleep(3)
    input_password = broswer.find_element(
        By.XPATH, "//input[@name='password']")
    input_password.send_keys(password)
    sleep(3)
    broswer.find_element(By.XPATH, "//a[@class='btn_login']").click()
    sleep(3)
    print("请扫码二维码，成功输入Y")
    sleep(20)
    broswer.get("https://mp.weixin.qq.com/")
    sleep(10)
    url = broswer.current_url
    cookies = broswer.get_cookies()
    for item in cookies:
        post[item['name']] = item['value']
    cookies_str = json.dumps(post)
    with open('cookie.txt', 'w+', encoding='utf-8') as f:
        f.write(cookies_str)
    param_list = url.split('?')[1].split('&')
    param_dict = {}

    for item in param_list:
        param_dict[item.split('=')[0]] = item.split('=')[1]
    return param_dict['token']


def search_mp_winxin(mp_name,token, def_request_cnt=30, history=0):
    url = 'https://mp.weixin.qq.com/'
    header = {
        'HOST': 'mp.weixin.qq.com',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'
    }
    with open('cookie.txt', 'r', encoding='utf-8') as r:
        cookie = r.read()
    cookies = json.loads(cookie)
    resq = requests.get(url=url, cookies=cookies, headers=header)
    search_url = "https://mp.weixin.qq.com/cgi-bin/searchbiz?"
    params = {
        'action': 'search_biz',
        'begin': 0,
        'count': 5,
        'query': mp_name,
        'token': token,
        'lang': 'zh_CN',
        'f': 'json',
        'ajax': 1
    }
    search_resq = requests.get(
        url=search_url, cookies=cookies, headers=header, params=params)
    gzh = search_resq.json().get('list')[0]
    mydb['gzh'].insert_one(gzh)

    fakeid = gzh.get("fakeid")

    appmsg_url = 'https://mp.weixin.qq.com/cgi-bin/appmsg?'
    params_data = {
        'action': 'list_ex',
        'begin': 0,
        'count': 10,
        'fakeid': fakeid,
        'type': '9',
        'query': '',
        'token': token,
        'lang': 'zh_CN',
        'f': 'json',
        'ajax': 1
    }
    appmsg_resq = requests.get(
        url=appmsg_url, cookies=cookies, headers=header, params=params_data)
    app_msg_list = appmsg_resq.json().get('app_msg_list')
    app_msg_cnt = appmsg_resq.json().get('app_msg_cnt')
    print(mp_name+"一共"+str(app_msg_cnt))
    for msg in app_msg_list:
        msg["fakeid"] = fakeid
        msg["name"] = mp_name
    firstLen = len(app_msg_list)
    print("第一次获取到"+str(firstLen)+"条数据")
    try:
        mydb["gzh_wz"].insert_many(app_msg_list)
    except:
        pass
    firstCount = (params_data['begin']+params_data['count'])

    # 如果有历史记录
    if history > 0:
        params_data['begin'] = history
    request_cnt = 1
    while app_msg_cnt >= (params_data['begin']+params_data['count']):
        try:
            request_cnt = request_cnt+1
            params_data['begin'] = params_data['begin']+params_data['count']
            sleepstart = random.randint(12, 50)
            sleepend = random.randint(55, 60)
            realsleep = random.randint(sleepstart, sleepend)
            print("休息"+str(realsleep)+"秒")
            sleep(realsleep)
            appmsg_resq = requests.get(
                url=appmsg_url, cookies=cookies, headers=header, params=params_data)
            app_msg_list = appmsg_resq.json().get('app_msg_list')
            app_msg_cnt = appmsg_resq.json().get('app_msg_cnt')
            print(mp_name+"一共"+str(app_msg_cnt))
            print("正在获取第"+str(params_data['begin']))
            # print(app_msg_list)
            for msg in app_msg_list:
                msg["fakeid"] = fakeid
                msg["name"] = mp_name
                try:
                    mydb["gzh_wz"].insert_one(msg)
                except:
                    pass
        except:
            print("接口请求次数为：%d" % (request_cnt))
            pass
def test_token(token,mp_name):
    import os
    if os.path.exists("token.txt"):
        with open('token.txt', 'r', encoding='utf-8') as r:
            token = r.read()
    url = 'https://mp.weixin.qq.com/'
    header = {
        'HOST': 'mp.weixin.qq.com',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'
    }
    with open('cookie.txt', 'r', encoding='utf-8') as r:
        cookie = r.read()
    cookies = json.loads(cookie)
    resq = requests.get(url=url, cookies=cookies, headers=header)
    search_url = "https://mp.weixin.qq.com/cgi-bin/searchbiz?"
    params = {
        'action': 'search_biz',
        'begin': 0,
        'count': 5,
        'query': mp_name,
        'token': token,
        'lang': 'zh_CN',
        'f': 'json',
        'ajax': 1
    }
    search_resq = requests.get(
        url=search_url, cookies=cookies, headers=header, params=params)
    base_resp = search_resq.json().get('base_resp')
    return base_resp["err_msg"]=="ok"
   

def main_task(mp_name,token=0, request_cnt=20, history=0):
    if test_token(mp_name,token):
        print("token是有效的：%s"%(token))
    else:
        print("token=%s是无效的，重新获取"%(token))
        token = mp_weixin_login()
        with open('token.txt', 'w+', encoding='utf-8') as f:
            f.write(token)
        print("新的token是：%s"%(token))
    search_mp_winxin(mp_name=mp_name,token=token, def_request_cnt=request_cnt, history=history)


if __name__ == '__main__':
    import sys
    mp_name = sys.argv[1]
    request_cnt = sys.argv[2]
    main_task(mp_name)
